package com.beiing.tianshuai.tianshuai.freshnews;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.UploadImgBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.presenter.DiscoveryPublishPresenter;
import com.beiing.tianshuai.tianshuai.freshnews.view.DiscoveryPublishViewImpl;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.HtmlUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.google.gson.Gson;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import jp.wasabeef.richeditor.RichEditor;
import okhttp3.ResponseBody;

/**
 * 发布发现
 * 发布发现
 * @author 不知道
 */
public class DiscoveryPublishActivity extends BaseActivity implements DiscoveryPublishViewImpl {

    @BindView(R.id.rich_editor)
    RichEditor mEditor;
    @BindView(R.id.toolbar_btn_publish)
    TextView mToolbarPublish;
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.discovery_publish_title)
    EditText mDiscoveryPublishTitle;
    @BindView(R.id.btn_font_type)
    ImageButton mBtnFontType;
    @BindView(R.id.btn_font_color)
    ImageButton mBtnFontColor;
    @BindView(R.id.btn_add_img)
    ImageButton mBtnAddImg;
    @BindView(R.id.toolbar_preview)
    TextView mToolbarPreview;
    @BindView(R.id.btn_font_h1)
    ImageButton mBtnFontH1;
    @BindView(R.id.btn_font_h2)
    ImageButton mBtnFontH2;
    @BindView(R.id.btn_font_h3)
    ImageButton mBtnFontH3;
    @BindView(R.id.menu_container)
    HorizontalScrollView mBottomMenu;
    @BindView(R.id.btn_font_h4)
    ImageButton mBtnFontH4;

    private Unbinder                                    mUnbinder;
    private static final String                         TAG = "DiscoveryPublishActivity";
    private static final int                            PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private Context                                     mContext;
    private boolean                                     isColorChanged;
    private DiscoveryPublishPresenter                   mPresenter;
    private String                                      mFreshCover;

    public static void star(Context context){
        Intent intent = new Intent(context, DiscoveryPublishActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_discovery_publish;
    }

    @Override
    protected void init() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initToolbar();
        initRichEditor();
        initPresenter();
        initListener();
    }

    private void initRichEditor() {
        mEditor.setEditorFontSize(DensityUtils.dp2px(mContext, 13));
        mEditor.setEditorHeight(DensityUtils.dp2px(mContext, 400));
        int i = DensityUtils.dp2px(mContext, 5);
        mEditor.setPadding(i, 0, i, i);
        mEditor.setPlaceholder("请输入正文");
        mEditor.setTextColor(0x2c2c2c);
        WebSettings settings = mEditor.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
    }

    private void initToolbar() {
        mToolbarPreview.setVisibility(View.VISIBLE);
        mToolbarTvTitle.setText("发布新鲜事");
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarIvBack.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                finish();
            }
        });
        mToolbarPublish.setVisibility(View.VISIBLE);
    }

    private void initPresenter() {
        mPresenter = new DiscoveryPublishPresenter(this);
    }

    private void initListener() {
        mEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mBottomMenu.setVisibility(View.VISIBLE);
                } else {
                    mBottomMenu.setVisibility(View.GONE);
                }
            }
        });

        // 预览
        mToolbarPreview.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String title = mDiscoveryPublishTitle.getText().toString();
                if (TextUtils.isEmpty(title)) {
                    showShortText("请输入标题");
                    return;
                }
                String content = getHtml(mEditor.getHtml());
                if (TextUtils.isEmpty(content)) {
                    showShortText("还没有输入任何内容噢~");
                    return;
                }
                Intent intent = new Intent(mContext, DiscoveryPreviewActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("content", content);
                startActivity(intent);
            }
        });

        // 发布
        mToolbarPublish.setOnClickListener(new BGAOnNoDoubleClickListener() {

            private String content;
            private String mTitle;
            private String mUid;

            @Override
            public void onNoDoubleClick(View v) {
                mTitle = mDiscoveryPublishTitle.getText().toString();
                mUid = UserInfoBean.getUid(mContext);
                content = mEditor.getHtml();
                LogUtils.i(getHtml(content), TAG);
                if (TextUtils.isEmpty(mTitle)) {
                    showShortText("请输入标题");
                    return;
                }
                if (TextUtils.isEmpty(content)) {
                    showShortText("还没有输入任何内容噢~");
                    return;
                }
                String[] htmlImageSrc = HtmlUtils.getHtmlImageSrc(mEditor.getHtml());
                if (htmlImageSrc.length >= 3) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < htmlImageSrc.length; i++) {
                        if (i == 0) {
                            stringBuilder.append(htmlImageSrc[i]);
                        } else {
                            stringBuilder.append(",").append(htmlImageSrc[i]);
                        }
                    }
                    mFreshCover = stringBuilder.toString();
                } else if (htmlImageSrc.length <= 2 && htmlImageSrc.length >= 1) {
                    mFreshCover = htmlImageSrc[0];
                } else {
                    mFreshCover = "";
                }
                mPresenter.getPublishResult(getHtml(content), mUid, mTitle, mFreshCover);
            }
        });

        // 加粗
        mBtnFontType.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mEditor.setBold();
            }
        });

        // 字体大小
        mBtnFontH1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(1);
            }
        });

        // 字体大小
        mBtnFontH2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(2);
            }
        });

        // 字体大小
        mBtnFontH3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(3);
            }
        });

        // 字体大小
        mBtnFontH4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(4);
            }
        });

        // 添加图片
        mBtnAddImg.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String html = mEditor.getHtml();
                if (!TextUtils.isEmpty(html)) {
                    String[] htmlImageSrc = HtmlUtils.getHtmlImageSrc(html);
                    if (htmlImageSrc.length >= 30) {
                        showShortText("最多可上传30张图片");
                        return;
                    }
                }
                checkSelfPermission();
            }
        });

        // 修改文字颜色
        mBtnFontColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setTextColor(isColorChanged ? Color.BLACK : Color.RED);
                isColorChanged = !isColorChanged;
            }
        });
    }

    private void uploadImg(File file) {
        mPresenter.getUploadImg(file);
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(DiscoveryPublishActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(DiscoveryPublishActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectMultiSelect();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectMultiSelect();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectMultiSelect() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String[] filesPath = photoList.toArray(new String[photoList.size()]);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.BatchFileCompressOptions();
                Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                    @Override
                    public void callback(boolean isSuccess, String[] outfile) {
                        List<String> outFiles = Arrays.asList(outfile);
                        for (int i = 0; i < outFiles.size(); i++) {
                            String s = outFiles.get(i);
                            uploadImg(new File(s));
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                  // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(DiscoveryPublishActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在加载，请稍后...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            finish();
            showShortText("提交成功");
        } else {
            showShortText("提交失败");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        showShortText("网络异常");
    }

    @Override
    public void getUploadResult(ResponseBody body) {
        try {
            String result = body.string();
            LogUtils.i(result, TAG);
            Gson gson = new Gson();
            UploadImgBean uploadImgBean = gson.fromJson(result, UploadImgBean.class);
            mEditor.insertImage(HttpRequestConstant.FRESH_COVER_URL + uploadImgBean.getData().getFreshcover(), "content_pic");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable, int i) {
        switch (i) {
            case 0:
                showShortText("发布失败");
                break;
            case 1:
                showShortText("图片上传失败");
                break;
                default:break;
        }
    }

    private String getHtml(String html) {
        html = "<html> \n" +
                "<head> \n" +
                "<style type=\\\"text/css\\\"> \n" +
                "body {font-size:15px;}\n" +
                "</style> \n" +
                "</head> \n" +
                "<body>\n" +
//                "<script type='text/javascript'>\n" +
//                "window.onload = function(){\n" +
//                "var $img = document.getElementsByTagName('img');\n" +
//                "for(var p in  $img){\n" +
//                "$img[p].style.width = '100%';\n" +
//                "$img[p].style.height ='auto'\n" +
//                "}\n" +
//                "}\n" +
//                "\t\t\t\t</script>" +
                html + "\n" +
                "</body>\n" +
                "</html>";
        return html;
    }
}
